from time import sleep

import yaml
from selenium import webdriver
from selenium.webdriver.remote.webdriver import WebDriver
from selenium.webdriver.remote.webelement import WebElement
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait


class BasePage:
    _base_url = ''
    def __init__(self,base_driver: WebDriver=None):
        if base_driver == None:
            self.driver = webdriver.Chrome()
            self.driver.get(self._base_url)
            self.driver.maximize_window()
            cookie = yaml.safe_load(open("../conf/cookie.yaml"))
            for c in cookie:
                self.driver.add_cookie(c)
            sleep(3)
            self.driver.get(self._base_url)
            self.driver.implicitly_wait(5)
        else:
            self.driver = base_driver

    # 关闭窗口
    def quit_window(self):
        self.driver.quit()

    # 查找元素
    def find(self,by,locator=None):
        if locator==None:
            webelement = self.driver.find_element(*by)
        else:
            webelement = self.driver.find_element(by=by,value=locator)
        return webelement

    # 查找多个元素
    def finds(self,by,locator=None):
        if locator==None:
            webelements = self.driver.find_elements(*by)
        else:
            webelements = self.driver.find_elements(by=by,value=locator)
        return webelements

    # 显示等待
    def webdriver_wait(self,by,locator):
        '''

        :param by: 定位方式
        :param locator: 元素定位
        :return: 返回元素
        '''
        ele:WebElement = WebDriverWait(self.driver,timeout=10).until(EC.element_to_be_clickable((by,locator)))
        return ele